<?php
/**
 *
 * Author: Lyu
 * Date: 2023/7/25
 * Time: 15:53
 */

namespace App\Service\Core\Admin\Role;

use App\Component\ListService\ListAbstract;
use App\Model\Core\Admin\AdminUserRoleModel;
use App\Service\ParamsService;

/**
 * @method $this setRoleIds($val)
 * @method $this setName($val)
 * @method $this setStatus($val)
 * @method $this setCreatedAtBegin($val)
 * @method $this setCreatedAtEnd($val)
 * @package App\Service\Core\Sys\User\Role
 */
class AdminUserRoleListService extends ListAbstract
{
    //允许获取的字段
    protected array $allow_fields = ['admin_user_role.*'];
    //允许获取的扩展字段
    protected array $allow_ext_fields = ['status_name', 'allow_edit'];
    //默认返回的字段
    protected array $default_fields = [];
    protected array $allow_sort = ['admin_user_role.role_id'];
    protected array $default_sort_by = ['admin_user_role.role_id' => 'desc'];


    protected function getQueryObj()
    {
        $query_obj = AdminUserRoleModel::getInstance()->getConnectionTable();
        $role_ids = $this->getParam('role_ids');
        $role_ids = easy_int_explode($role_ids);
        if (!empty($role_ids)) {
            $query_obj->whereIn('admin_user_role.role_id', $role_ids);
        }
        $name = $this->getParam('name');
        if (!empty($name)) {
            $query_obj->where('admin_user_role.name', 'like', '%' . $name . '%');
        }
        $status = $this->getParam('status');
        if (is_numeric($status)) {
            $query_obj->where('admin_user_role.status', $status);
        }
        //开始时间
        $created_at_begin = $this->getParam('created_at_begin');
        if (!empty($created_at_begin)) {
            $created_at_begin = date('Y-m-d H:i:s', strtotime($created_at_begin));
            $query_obj->where('admin_user_role.created_at', '>=', $created_at_begin);
        }
        //结束时间
        $created_at_end = $this->getParam('created_at_end');
        if (!empty($created_at_end)) {
            $created_at_end = date('Y-m-d H:i:s', strtotime($created_at_end));
            $query_obj->where('admin_user_role.created_at', '<=', $created_at_end);
        }
        return $query_obj;
    }

    /**
     * 获取扩展字段
     * @param array $row
     * @return array
     */
    protected function getExtField(array $row)
    {
        if (easy_in_array('status_name', $this->ext_fields)) {
            $row['status_name'] = ParamsService::$status[$row['status']];
        }
        $row['allow_edit'] = in_array($row['name'], ParamsService::$admin_user_role_init) ? 1 : 0;
        return $row;
    }
}
